package cc.rengu.igas.momp.core.service.trans;

import cc.rengu.igas.momp.common.constant.CommonConstant;
import cc.rengu.igas.momp.common.dao.StatCashierUserInfoMapper;
import cc.rengu.igas.momp.common.dao.impl.StatCashierUserInfoMapperImpl;
import cc.rengu.igas.momp.common.entity.CcbMcDetailListInObj;
import cc.rengu.igas.momp.common.entity.CcbMcDetailListOutObj;
import cc.rengu.igas.momp.common.enums.McTypeEnum;
import cc.rengu.igas.momp.common.enums.QueryRoleEnum;
import cc.rengu.igas.momp.common.enums.QueryTypeEnum;
import cc.rengu.igas.momp.common.enums.RespCodeEnum;
import cc.rengu.igas.momp.common.util.CommonMessageCheck;
import cc.rengu.igas.momp.common.util.MompDateUtil;
import cc.rengu.igas.momp.facade.bean.CashierCashbackToCashierDetailInfoBean;
import cc.rengu.igas.momp.facade.request.QueryCashbackToCashierDetailRequest;
import cc.rengu.igas.momp.facade.response.QueryCashbackToCashierDetailResponse;
import cc.rengu.oltp.service.base.RadpService;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.bean.PageInfo;
import cc.rengu.oltp.utility.bean.PageResult;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.base.StringUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Jinan Liu
 * @date 2020/4/7 21:54
 * @description 收银员营销打款明细-收银员返现类活动返现明细查询功能实现(银行)
 */
public class QueryCashbackToCashierDetailService extends RadpService {
    private String globalInstId;
    private String globalQueryType;
    private String globalQueryRole;
    private String globalQueryOrgId;
    private String mcType;
    private String mcNo;
    private String mchntNo;

    @Override
    protected int bizInit(String s) {
        return CommonConstant.PROCESS_SUCCESS;
    }

    @Override
    protected int bizProcess(String s, int i) {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();

        try {

            QueryCashbackToCashierDetailRequest queryCashbackToCashierDetailRequest = new QueryCashbackToCashierDetailRequest();
            ConvertUtil.convertOutput(queryCashbackToCashierDetailRequest);

            QueryCashbackToCashierDetailResponse queryCashbackToCashierDetailResponse = new QueryCashbackToCashierDetailResponse();
            queryCashbackToCashierDetailResponse.setHeader(queryCashbackToCashierDetailRequest.getHeader());
            BizResponse<QueryCashbackToCashierDetailResponse> bizResponse = new BizResponse<>();
            bizResponse.setResult(queryCashbackToCashierDetailResponse);

            globalInstId = queryCashbackToCashierDetailRequest.getHeader().getInstId();
            String timeStamp = new SimpleDateFormat(CommonConstant.TIMESTAMP_FORMAT).format(new Date());
            String oprId = queryCashbackToCashierDetailRequest.getQueryId();
            globalQueryOrgId = queryCashbackToCashierDetailRequest.getQueryOrgId();

            rglog.info("机构<{}>在<{}>由<{}>开始查询收银员返现明细列表信息流程", globalInstId, timeStamp, oprId);

            globalQueryType = queryCashbackToCashierDetailRequest.getQueryType();
            globalQueryRole = queryCashbackToCashierDetailRequest.getQueryRole();
            mcType = queryCashbackToCashierDetailRequest.getMcType();
            mcNo = queryCashbackToCashierDetailRequest.getMcNo();
            mchntNo = queryCashbackToCashierDetailRequest.getMchntNo();
            /* 报文检查 */
            CommonMessageCheck.checkBizMessageHeader(globalQueryType, oprId, globalQueryRole, rglog);

            /* 检查操作员所属机构号 */
            if (StringUtil.isNullorEmpty(globalQueryOrgId)) {
                rglog.error("法人机构号<{}>的操作员<{}>的所属机构为空!", globalInstId, oprId);
                throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
            }
            if (null != mcType) {
                if (!McTypeEnum.CASHER_CASHBACK.getMcTypeCode().equals(mcType)) {
                    /* 不支持的营销活动类型 */
                    rglog.error("<{}>, INST_ID=<{}>, MC_TYPE=<{}>", RespCodeEnum.NOT_SUPPORTED_MC_TYPE_ERROR.getRespDesc(), globalInstId, mcType);
                    throw new BizException(RespCodeEnum.NOT_SUPPORTED_MC_TYPE_ERROR.getRespCode(), RespCodeEnum.NOT_SUPPORTED_MC_TYPE_ERROR.getRespDesc());
                }
            }
            // 服务调用
            BizResponse<QueryCashbackToCashierDetailResponse> bizResponseNew = queryCashierCashbackDetail(xmlTreeUtil, queryCashbackToCashierDetailRequest, queryCashbackToCashierDetailResponse);

            ConvertUtil.convertInput(bizResponseNew.getResult());

        } catch (BizException e) {
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, e.getCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, e.getMessage());
                xmlTreeUtil.setXmlTreeStringValue(CommonConstant.KEY_RESPDESC, e.getMessage());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e1));
            }
        } catch (Exception e) {
            rglog.error(StringUtil.ExceptionToString(e));
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespDesc());
                xmlTreeUtil.setXmlTreeStringValue(CommonConstant.KEY_RESPDESC, e.getMessage());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e));
            }
        }

        return CommonConstant.PROCESS_SUCCESS;
    }

    @Override
    protected int bizTerminate(String s) {
        return CommonConstant.PROCESS_SUCCESS;
    }

    /**
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/3/17 00:28
     * @description 查询收银员返现类营销活动明细列表信息
     * @return: void
     */
    private BizResponse<QueryCashbackToCashierDetailResponse> queryCashierCashbackDetail(XmlTreeUtil xmlTreeUtil, QueryCashbackToCashierDetailRequest queryCashbackToCashierDetailRequest, QueryCashbackToCashierDetailResponse queryCashbackToCashierDetailResponse) throws Exception {

        BizResponse<QueryCashbackToCashierDetailResponse> bizResponse = new BizResponse<>();
        List<CashierCashbackToCashierDetailInfoBean> cashbackToCashierDetailInfoBeans;
        List<CcbMcDetailListOutObj> ccbMcDetailListOutObjList = new ArrayList<>();
        CcbMcDetailListInObj ccbMcDetailListInObj = setupDatabaseInputObject(queryCashbackToCashierDetailRequest);
        PageResult pageResult = null;
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageIndex(Integer.parseInt(queryCashbackToCashierDetailRequest.getPageIndex()));
        pageInfo.setPageSize(Integer.parseInt(queryCashbackToCashierDetailRequest.getPageSize()));
        if (QueryTypeEnum.BANK_QUERY_TYPE.getQueryTypeCode().equals(globalQueryType)) {
            /* 银行人员 */
            /* 查询营销活动基本信息 */
            /* 查询营销活动机构信息 */
            /* 判断是否有权限查询数据 */
            //银行录入岗有权限查看数据
            if (QueryRoleEnum.BANK_BASIC_QUERY_ROLE.getQueryRoleCode().equals(globalQueryRole)) {
                //如果上送营销活动编号，按营销活动编号查询
                if (!StringUtil.isNullorEmpty(mcNo)) {
                    ccbMcDetailListInObj.setMcNo(mcNo);
                    try {
                        pageResult = selectCashierCashbackDetail(ccbMcDetailListInObj, pageInfo);
                    } catch (Exception e) {
                        rglog.error(e.getMessage());
                    }
                } else {
                    //如果不上送营销活动编号，取机构下所有收银员数据
                    try {
                        pageResult = selectCashierCashbackDetail(ccbMcDetailListInObj, pageInfo);
                    } catch (Exception e) {
                        rglog.error(e.getMessage());
                    }
                }
            } else {
                /* 银行审批、发布岗无权限查询 */
                rglog.error("当前<{}>角色的查询用户<{}>无权限查看数据!", globalQueryRole, globalQueryType);
                throw new BizException(RespCodeEnum.NO_AUTHORIZATION_TO_QUERY_ERROR.getRespCode(), RespCodeEnum.NO_AUTHORIZATION_TO_QUERY_ERROR.getRespDesc());
            }

        } else {
            /* 代理商、商户、收银员或用户 */
            rglog.error("当前<{}>角色的查询用户<{}>无权限查看数据!", globalQueryRole, globalQueryType);
            throw new BizException(RespCodeEnum.NO_AUTHORIZATION_TO_QUERY_ERROR.getRespCode(), RespCodeEnum.NO_AUTHORIZATION_TO_QUERY_ERROR.getRespDesc());
        }


        /* 根据取出记录条数做对应处理 */
        if (null == pageResult || null == pageResult.getResult() || pageResult.getResult().isEmpty()) {
            rglog.info("根据查询条件查询到0条收银员返现活动明细信息!");

            queryCashbackToCashierDetailResponse.setTotalPage(CommonConstant.ZERO_COMMON_CONSTANT);
            queryCashbackToCashierDetailResponse.setTotalRows(CommonConstant.ZERO_COMMON_CONSTANT);

        } else {

            for (Object object : pageResult.getResult()) {
                ccbMcDetailListOutObjList.add((CcbMcDetailListOutObj) object);
            }

            rglog.info("SIZE=<{}>", pageResult.getResult().size());

            cashbackToCashierDetailInfoBeans = ccbMcDetailListOutObjList.stream().map(this::fetchMchntCashbackData).collect(Collectors.toList());
            queryCashbackToCashierDetailResponse.setCashbackDetailList(cashbackToCashierDetailInfoBeans);

            queryCashbackToCashierDetailResponse.setTotalPage(Integer.toString(pageResult.getPageInfo().getTotalPage()));
            queryCashbackToCashierDetailResponse.setTotalRows(Integer.toString(pageResult.getPageInfo().getTotalRows()));

        }

        bizResponse.setRspSysId(ChannelEnum.MOMP.getChannelType());
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());

        queryCashbackToCashierDetailResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        queryCashbackToCashierDetailResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        queryCashbackToCashierDetailResponse.setPageIndex(queryCashbackToCashierDetailRequest.getPageIndex());
        queryCashbackToCashierDetailResponse.setPageSize(queryCashbackToCashierDetailRequest.getPageSize());

        bizResponse.setResult(queryCashbackToCashierDetailResponse);

        return bizResponse;
    }

    /**
     * 数据库查询前赋值数据库实体类入参
     *
     * @param queryCashbackToCashierDetailRequest 收银员返现明细列表查询接口请求对象(银行)
     * @return cc.rengu.igas.momp.common.entity.CcbMcListInfoInObj 收银员返现明细列表查询使用实体类入参
     * @author Jinan Liu
     * @date 2020/5/28 12:57
     */
    private CcbMcDetailListInObj setupDatabaseInputObject(QueryCashbackToCashierDetailRequest queryCashbackToCashierDetailRequest) {

        CcbMcDetailListInObj ccbMcDetailListInObj = new CcbMcDetailListInObj();

        /* 机构编码 */
        ccbMcDetailListInObj.setInstId(globalInstId);
        rglog.info("INST_ID=<{}>", globalInstId);
        /* 查询收银员账号 */
        ccbMcDetailListInObj.setAcctNo(queryCashbackToCashierDetailRequest.getAcctNo());
        /* 打款状态 */
        ccbMcDetailListInObj.setCashbackStatus(queryCashbackToCashierDetailRequest.getCashbackStatus());
        /* 打款日期 */
        if (!StringUtil.isNullorEmpty(queryCashbackToCashierDetailRequest.getCashbackDate())) {
            ccbMcDetailListInObj.setCashbackTime(queryCashbackToCashierDetailRequest.getCashbackDate().substring(0, 4).concat("-").concat(queryCashbackToCashierDetailRequest.getCashbackDate().substring(4, 6).concat("-").concat(queryCashbackToCashierDetailRequest.getCashbackDate().substring(6, 8))));
        }
        //商户号
        ccbMcDetailListInObj.setUserInst(queryCashbackToCashierDetailRequest.getMchntNo());
        return ccbMcDetailListInObj;
    }

    /**
     * 收银员返现明细查询（通用）
     *
     * @param ccbMcDetailListInObj 收银员返现活动明细列表查询使用实体类入参
     * @param pageInfo             数据库操作分页请求实体类
     * @return cc.rengu.oltp.utility.bean.PageResult 数据库操作分页应答实体类
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/28 13:13
     */
    private PageResult selectCashierCashbackDetail(CcbMcDetailListInObj ccbMcDetailListInObj, PageInfo pageInfo) throws Exception {

        StatCashierUserInfoMapper statCashierUserInfoMapper = new StatCashierUserInfoMapperImpl();
        return statCashierUserInfoMapper.selectCashierCashbackDetailAll(ccbMcDetailListInObj, pageInfo);

    }

    /**
     * @param ccbMcDetailListOutObj
     * @return cc.rengu.igas.momp.facade.bean.CashierCashbackToCashierDetailInfoBean
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/4/8 11:20
     */
    private CashierCashbackToCashierDetailInfoBean fetchMchntCashbackData(CcbMcDetailListOutObj ccbMcDetailListOutObj) {

        CashierCashbackToCashierDetailInfoBean cashierCashbackToCashierDetailInfoBean = new CashierCashbackToCashierDetailInfoBean();

        /** 营销活动编号 */
        cashierCashbackToCashierDetailInfoBean.setMcNo(ccbMcDetailListOutObj.getMcNo());
        /** 收银员标识 */
        cashierCashbackToCashierDetailInfoBean.setUserId(ccbMcDetailListOutObj.getUserId());
        /** 收银员所属主体 */
        cashierCashbackToCashierDetailInfoBean.setUserInst(ccbMcDetailListOutObj.getUserInst());
        /** 收银员卡号 */
        cashierCashbackToCashierDetailInfoBean.setAcctNo(ccbMcDetailListOutObj.getAcctNo());
        /** 打款状态 */
        cashierCashbackToCashierDetailInfoBean.setCashbackStatus(ccbMcDetailListOutObj.getCashbackStatus());
        /** 打款类型 */
        cashierCashbackToCashierDetailInfoBean.setCashbackMethod(ccbMcDetailListOutObj.getCashbackMethod());
        /** 打款金额 */
        cashierCashbackToCashierDetailInfoBean.setCashbackAmt(ccbMcDetailListOutObj.getCashbackAmt());
        /** 打款时间 */
        cashierCashbackToCashierDetailInfoBean.setCashbackTime(ccbMcDetailListOutObj.getCashbackTime());
        //商户号
        cashierCashbackToCashierDetailInfoBean.setMchntNo(ccbMcDetailListOutObj.getUserInst());
        return cashierCashbackToCashierDetailInfoBean;
    }
}

